package com.henry.base.concurrency.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class Calculator extends RecursiveTask<Long> {
    private static final int THRESHOLD=10;
    private long start;
    private long end;

    public Calculator(long start, long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        long sum=0;
        if (end - start > THRESHOLD) {
            for (long i = start; i < end; i++) {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                sum += i;
            }
        } else {
//            while (start<end){
//                Calculator calculator = new Calculator(start, start+100);
//                start=start+100;
//                calculator.fork();
//            }
            long mid = (start+end)/2;
            Calculator left = new Calculator(start, mid);
            Calculator right = new Calculator(mid+1, end);
            left.fork();
            right.fork();
            sum=left.join()+right.join();
        }
        return sum;

    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        long beg = System.nanoTime();
        ForkJoinTask<Long> result = forkJoinPool.submit(new Calculator(0L, 10000L));
        System.out.println(result.get());
        long end1 = System.nanoTime();

        System.out.println((end1-beg)/1000/1000);
    }
}
